package com.forum.model.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import com.forum.model.pojo.SubForum;
import com.forum.model.util.SessionManager;

public class SubForumDAO implements GenericDAO<SubForum, String> {

	private Session session;

	@Override
	public boolean insert(SubForum subForum) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(subForum);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(SubForum subForum) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(subForum);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(SubForum subForum) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(subForum);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public SubForum getObjectById(String name) {
		SubForum subForum = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			subForum = (SubForum) session.get(SubForum.class, name);
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return subForum;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<SubForum> getAll() {
		List<SubForum> all = new ArrayList<SubForum>();

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<SubForum>) session.createQuery("from SubForum").list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}
}
